<template>
  <!-- 条件搜索框 -->
  <el-form :inline="true" label-width="80px">
    <el-form-item label="菜名">
      <el-input v-model="page.dishName" placeholder="请填写菜名" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="search">查询</el-button>
    </el-form-item>
  </el-form>

  <!-- 新增 批量删除 -->
  <el-button type="primary" @click="add">新增</el-button>
  <el-button type="danger" @click="deleteSelected">批量删除</el-button>

  <!-- 菜单列表 -->
  <el-table :data="menuList" @selection-change="handleSelectionChange" border style="width: 100%; margin: 3px 0;">
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column prop="tid" label="ID" />
    <el-table-column prop="dishName" label="菜名" />
    <el-table-column prop="dishImageUrl" label="图片">
      <template #default="scope">
        <img :src="scope.row.dishImageUrl" alt="菜图" style="width: 100px; height: auto;" />
      </template>
    </el-table-column>
    <el-table-column prop="popularity" label="人气" />
    <el-table-column prop="description" label="描述" />
    <el-table-column prop="author" label="作者" />
    <el-table-column prop="authorImageUrl" label="作者图片">
      <template #default="scope">
        <img :src="scope.row.authorImageUrl" alt="作者图" style="width: 100px; height: auto;" />
      </template>
    </el-table-column>
    <el-table-column label="操作" width="150">
      <template #default="scope">
        <el-button size="small" type="primary" @click="edit(scope.$index, scope.row)">
          编辑
        </el-button>
        <el-button size="small" @click="del(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination
      v-model:current-page="page.pageIndex"
      v-model:page-size="page.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, prev, pager, next, sizes"
      :total="page.total"
      @size-change="handleSizeChange"
      @current-change="currentPage"
  />

  <!-- 新增/编辑对话框 -->
  <el-dialog v-model="dialogVisible" width="500" title="菜品信息页" draggable @close="dialogClose">
    <el-form label-width="80px">
      <el-form-item label="菜名">
        <el-input v-model="form.dishName" placeholder="请填写菜名" />
      </el-form-item>
      <el-form-item label="图片">
        <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleDishImageSuccess"
            :before-upload="beforeDishImageUpload"
            :http-request="uploadDishImage"
        >
          <img v-if="form.dishImageUrl" :src="form.dishImageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><IEpPlus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="人气">
        <el-input v-model="form.popularity" placeholder="请填写人气" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="form.description" placeholder="请填写描述" />
      </el-form-item>
      <el-form-item label="作者">
        <el-input v-model="form.author" placeholder="请填写作者" />
      </el-form-item>
      <el-form-item label="作者图片">
        <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="handleAuthorImageSuccess"
            :before-upload="beforeAuthorImageUpload"
            :http-request="uploadAuthorImage"
        >
          <img v-if="form.authorImageUrl" :src="form.authorImageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><IEpPlus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import axios from "axios";
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';

let page = ref({
  dishName: "",
  pageIndex: 1,
  pageSize: 10,
  total: 0
});

let menuList = ref([]);
let selectedRows = ref([]);

// 初始化菜单数据
let initData = () => {
  axios.post("/admin/todaymenu/search", page.value)
      .then(response => {
        const result = response.data;
        if (result.code === 200 && result.date) {
          const data = result.date;
          menuList.value = data.list || [];
          page.value.total = data.total || 0;
        } else {
          ElMessage({
            type: 'error',
            message: '数据获取失败！',
            showClose: true
          });
        }
      })
      .catch(error => {
        console.error('Error fetching data:', error);
        ElMessage({
          type: 'error',
          message: '数据获取失败！',
          showClose: true
        });
      });
};

// 当点击新页码时触发
const currentPage = (val) => {
  page.value.pageIndex = val;
  initData();
};

// 当每页条数改变时触发
const handleSizeChange = (val) => {
  page.value.pageSize = val;
  initData();
};

// 根据条件查询
let search = () => {
  page.value.pageIndex = 1;
  initData();
};

// 处理多选变化
const handleSelectionChange = (val) => {
  selectedRows.value = val;
};

// 新增
let dialogVisible = ref(false);
let form = ref({
  tid: "",
  dishName: "",
  dishImageUrl: "",
  popularity: "",
  description: "",
  author: "",
  authorImageUrl: ""
});

let add = () => {
  form.value = {
    tid: "",
    dishName: "",
    dishImageUrl: "",
    popularity: "",
    description: "",
    author: "",
    authorImageUrl: ""
  };
  dialogVisible.value = true;
};

// 编辑
let edit = (index, row) => {
  form.value = { ...row };
  dialogVisible.value = true;
};

// 保存
let save = () => {
  axios.post("/admin/todaymenu/save", form.value)
      .then(response => {
        if (response.data.code === 200) {
          ElMessage({
            type: 'success',
            message: '保存成功！',
            showClose: true
          });
          dialogVisible.value = false;
          initData();
        } else {
          ElMessage({
            type: 'error',
            message: '保存失败！',
            showClose: true
          });
        }
      })
      .catch(error => {
        console.error('Error saving data:', error);
        ElMessage({
          type: 'error',
          message: '保存失败！',
          showClose: true
        });
      });
};

// 删除
let del = (index, row) => {
  ElMessageBox.confirm('确认删除?', '删除菜品', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(() => {
    axios.delete(`/admin/todaymenu/delete/${row.tid}`)
        .then(response => {
          if (response.data.code === 200) {
            ElMessage({
              type: 'success',
              message: '删除成功！',
              showClose: true
            });
            initData();
          } else {
            ElMessage({
              type: 'error',
              message: '删除失败！',
              showClose: true
            });
          }
        })
        .catch(error => {
          console.error('Error deleting data:', error);
          ElMessage({
            type: 'error',
            message: '删除失败！',
            showClose: true
          });
        });
  }).catch(() => {
    console.log('取消');
  });
};

// 批量删除
let deleteSelected = () => {
  if (selectedRows.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请至少选择一个要删除的菜品',
      showClose: true
    });
    return;
  }

  ElMessageBox.confirm('确认删除选中的菜品?', '批量删除菜品', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  }).then(() => {
    const tids = selectedRows.value.map(row => row.tid);
    axios.post("/admin/todaymenu/deleteTodaymenus", tids)
        .then(response => {
          if (response.data.code === 200) {
            ElMessage({
              type: 'success',
              message: '删除成功！',
              showClose: true
            });
            initData();
          } else {
            ElMessage({
              type: 'error',
              message: '删除失败！',
              showClose: true
            });
          }
        })
        .catch(error => {
          console.error('Error deleting batch data:', error);
          ElMessage({
            type: 'error',
            message: '删除失败！',
            showClose: true
          });
        });
  }).catch(() => {
    console.log('取消');
  });
};

// 上传菜品图片
let uploadDishImage = (params) => {
  const formData = new FormData();
  formData.append("file", params.file);

  axios.post("/upload", formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
      .then(response => {
        form.value.dishImageUrl = response.data.date;
      })
      .catch(error => {
        console.error('Error uploading dish image:', error);
      });
};

// 上传作者图片
let uploadAuthorImage = (params) => {
  const formData = new FormData();
  formData.append("file", params.file);

  axios.post("/upload", formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
      .then(response => {
        form.value.authorImageUrl = response.data.date;
      })
      .catch(error => {
        console.error('Error uploading author image:', error);
      });
};

// 图片上传成功回调
let handleDishImageSuccess = (response) => {
  form.value.dishImageUrl = response.data.date;
};

let handleAuthorImageSuccess = (response) => {
  form.value.authorImageUrl = response.data.date;
};

// 图片上传前的回调
let beforeDishImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
  }
  return (isJPG || isPNG) && isLt2M;
};

let beforeAuthorImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg';
  const isPNG = file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!');
  }
  return (isJPG || isPNG) && isLt2M;
};

// 对话框关闭时重置表单
let dialogClose = () => {
  form.value = {
    tid: "",
    dishName: "",
    dishImageUrl: "",
    popularity: "",
    description: "",
    author: "",
    authorImageUrl: ""
  };
};

// 重置表单
let resetForm = () => {
  form.value = {
    tid: "",
    dishName: "",
    dishImageUrl: "",
    popularity: "",
    description: "",
    author: "",
    authorImageUrl: ""
  };
};

onMounted(() => {
  initData();
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>